package com.glela.controller;

import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.UserAddress;
import com.glela.platform.model.UserIdCard;
import com.glela.platform.model.request.RequestUserModel;
import com.glela.platform.model.request.ZoneRequest;
import com.glela.platform.model.response.ProvinceVo;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.UserAddressService;
import com.glela.platform.service.UserIdCardService;
import com.glela.platform.util.ParameterUtils;
import com.glela.platform.vo.UserAddressVo;

@Controller
@RequestMapping(value = "/userAddress", produces = "application/json;charset=UTF-8")
public class UserAddressController extends BaseController {
	@Autowired
	private UserAddressService userAddressService;
	@Autowired
	private  UserIdCardService userIdCardService;

	/**
	 * 我的收货地址列表
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/listUserAddressPage", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> listUserAddressPage(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			List<UserAddressVo> UserAddress = userAddressService.listUserAddressPage(requestUserModel.getUserId(), requestUserModel.getStartIndex(), requestUserModel.getPageSize());
			return new ResponseEntity<>(new ResponseResultModel<List<UserAddressVo>>(UserAddress), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("我的收货地址列表异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 添加收货地址
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addUserAddress", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> addUserAddress(@RequestBody UserAddress addUserAddress) {
		try {
			if (addUserAddress.getUserId() == null || StringUtils.isBlank(addUserAddress.getLinkMan()) || StringUtils.isBlank(addUserAddress.getMobile()) || StringUtils.isBlank(addUserAddress.getProvince()) || StringUtils.isBlank(addUserAddress.getCity()) || StringUtils.isBlank(addUserAddress.getArea()) || StringUtils.isBlank(addUserAddress.getAddress())) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			if (addUserAddress.getMobile().trim().length() < 11 || addUserAddress.getMobile().trim().length() > 11) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20164), HttpStatus.OK);
			}
			trimString(addUserAddress);
			if (addUserAddress.getIsNeedCheck() == 1) {// 需要实名认证
				UserIdCard userIdCard = userIdCardService.checkIdcard(addUserAddress.getIdNumber(), addUserAddress.getLinkMan(), addUserAddress.getUserId());
				if (userIdCard.getCode() != 1) {// 未通过校验
					addUserAddress.setVerifyNumber(userIdCardService.IdcardTimes(addUserAddress.getUserId()));
					return new ResponseEntity<>(new ResponseResultModel<UserAddressVo>(userIdCard.getCode(),userIdCard.getMessage(),new UserAddressVo(addUserAddress)), HttpStatus.OK);
				}
			}
			int i = userAddressService.addUserAddress(addUserAddress);
			if (i == 1) {
				addUserAddress.setVerifyNumber(userIdCardService.IdcardTimes(addUserAddress.getUserId()));
				return new ResponseEntity<>(new ResponseResultModel<UserAddressVo>(ErrorEnum.C10000,new UserAddressVo(addUserAddress)), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("添加收货地址异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 修改收货地址
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/changeUseraddressByuserId", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> changeUseraddressByuserId(@RequestBody UserAddress UserAddress) {
		try {
			if (UserAddress.getId() == null || UserAddress.getUserId() == null || UserAddress.getLinkMan() == null || UserAddress.getMobile() == null || UserAddress.getProvince() == null || UserAddress.getCity() == null || UserAddress.getArea() == null || UserAddress.getStreet() == null || UserAddress.getAddress() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			if (UserAddress.getMobile().trim().length() < 11 || UserAddress.getMobile().trim().length() > 11) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20164), HttpStatus.OK);
			}
			UserAddress beforeAddress = userAddressService.selectUserAddressById(UserAddress.getId());
			trimString(UserAddress);
			// 客户端认为需要实名认证
			if (UserAddress.getIsNeedCheck() == 1) {
				if (ParameterUtils.validParams(UserAddress.getIdNumber())) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
				}
				if (StringUtils.equals(beforeAddress.getLinkMan(), UserAddress.getLinkMan()) && StringUtils.equals(beforeAddress.getIdNumber(), UserAddress.getIdNumber())) {// 已实名制的信息未发生变化
					UserAddress.setVerifyNumber(userIdCardService.IdcardTimes(UserAddress.getUserId()));
				} else {
					UserIdCard userIdCard = userIdCardService.checkIdcard(UserAddress.getIdNumber(), UserAddress.getLinkMan(), UserAddress.getUserId());
					UserAddress.setVerifyNumber(userIdCardService.IdcardTimes(UserAddress.getUserId()));
					if (userIdCard.getCode() != 1) {// 未通过校验
						return new ResponseEntity<>(new ResponseResultModel<UserAddressVo>(userIdCard.getCode(), userIdCard.getMessage(), new UserAddressVo(UserAddress)), HttpStatus.OK);
					}
				}
			} else if (UserAddress.getIsNeedCheck() == 0 && !StringUtils.equals(beforeAddress.getLinkMan(), UserAddress.getLinkMan())) {
				UserAddress.setIdNumber("");
			}
			int i = userAddressService.changeUseraddressByuserId(UserAddress);
			if (i == 1) {
				return new ResponseEntity<>(new ResponseResultModel<UserAddressVo>(ErrorEnum.C10000, new UserAddressVo(UserAddress)), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("修改收货地址异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询默认收货地址
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@RequestMapping(value = "/selectDefaultAddress", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectDefaultAddress(@RequestBody RequestUserModel requestUserModel) {
		String rslt=null;
		try {
			if (ParameterUtils.validParams(requestUserModel.getUserId())) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}

			UserAddressVo defaultAddress = userAddressService.selectDefaultAddress(requestUserModel.getUserId());
			if (defaultAddress == null) {//无收货地址
				defaultAddress =new UserAddressVo();
				defaultAddress.setUserId(requestUserModel.getUserId());
				defaultAddress.setVerifyNumber(userIdCardService.IdcardTimes(requestUserModel.getUserId()));
				rslt = toResultModelJSON(ErrorEnum.C20129,defaultAddress);
			} else {
				defaultAddress.setVerifyNumber(userIdCardService.IdcardTimes(requestUserModel.getUserId()));
				rslt = toResultModelJSON(defaultAddress);
			}
		
		} catch (Exception e) {
			getLOGGER().error("查询用户[{}]默认收货地址失败：{}", requestUserModel.getUserId(), e.getMessage(), e);
			rslt = toErrorModelJSON(ErrorEnum.C20129);
		}
		return toRespEntity(rslt);
	}

	/**
	 * 删除收货地址
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/removeUseraddressByuserId", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> removeUseraddressByuserId(@RequestBody UserAddress UserAddress) {
		try {
			if (UserAddress.getUserId() == null || UserAddress.getId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			int i = userAddressService.removeUseraddressByuserId(UserAddress.getUserId(), UserAddress.getId());
			if (i == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("删除收货地址地址异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 修改默认收货地址
	 * 
	 * @param UserAddress
	 * @return
	 */
	@RequestMapping(value = "/updateUserAddressDefaultByUserId", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateUserAddressDefaultByUserId(@RequestBody UserAddress model) {
		try {
			if (ParameterUtils.validParams(model.getUserId(), model.getId())) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			int i = userAddressService.changeDefaultAddress(model.getUserId(), model.getId());
			if (i > 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20143), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("修改默认收货地址异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 获取中国所有省市区数据
	 * 
	 * @author 卫耀华
	 * @return
	 */
	@RequestMapping(value = "/provinceCityArea", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> provinceCityArea() {
		try {
			List<ProvinceVo> list = userAddressService.provinceCityArea();
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("获取中国所有省市区数据异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	* **********************************************
	* @Title: zone 
	* @Description: 获取行政区划接口 
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年12月13日 上午10:22:32 
	* **********************************************
	 */
	@RequestMapping(value = "/zone", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> zone(@RequestBody ZoneRequest request) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(request.getZongLevel())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			int parentId = 0;
			if (request.getZongLevel() != 1) {
				if (ParameterUtils.validParams(request.getParentId())) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
				}
				parentId = request.getParentId();
			}
			tempKey = StringUtils.EMPTY + request.getZongLevel() + "-" + parentId;
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				List<Map<String,Object>> list = userAddressService.getZoneByLevelAndParentId(request.getZongLevel(),parentId);
				if (CollectionUtils.isEmpty(list)) {
					rslt = toErrorModelJSON(ErrorEnum.C44001);
				} else {
					rslt = toResultModelJSON(list);
				}
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("获取行政区划数据异常", e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(tempKey, rslt, 1800));
	}
	
	/**
	* **********************************************
	* @Title: branchBankList 
	* @Description: 查询银行分行接口：根据市、银行查询分行信息
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年12月13日 下午1:42:18 
	* **********************************************
	 */
	@RequestMapping(value = "/branchBankList", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> branchBankList(@RequestBody ZoneRequest request) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(request.getBankId(), request.getCityId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			tempKey = StringUtils.EMPTY + request.getBankId() + "-" + request.getCityId();
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				Map<String,List<Map<String, Object>>> branchBankMap = userAddressService.getBranchBankList(request.getBankId(),request.getCityId());
				if (branchBankMap == null) {
					rslt = toErrorModelJSON(ErrorEnum.C44001);
				} else {
					rslt = toResultModelJSON(branchBankMap);
				}
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("获取行政区划数据异常", e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(tempKey, rslt, 1800));
	}

	/** 置空字段 */
	private void trimString(UserAddress userAddress) {
		userAddress.setLinkMan(StringUtils.trimToEmpty(userAddress.getLinkMan()));
		userAddress.setMobile(StringUtils.trimToEmpty(userAddress.getMobile()));
		userAddress.setAddress(StringUtils.stripToEmpty(userAddress.getAddress()));
	}
}
